#!/usr/bin/python3
# -*- coding: utf-8 -*-

from flask import request

def get_token_from_request():
    """从请求中获取token
    
    优先级顺序：
    1. 自定义token头
    2. 查询参数中的token
    3. 请求体中的token (仅对POST/PUT等带有请求体的方法)
    4. Authorization头 (Bearer token格式，作为备选)
    
    Returns:
        str: token字符串，如果不存在则返回None
    """
    token = None
    
    # 1. 从自定义token头获取
    token = request.headers.get('token')
    
    # 2. 从查询参数获取token
    if not token:
        token = request.args.get('token')
    
    # 3. 从请求体获取token (用于POST/PUT等请求)
    if not token and request.method in ['POST', 'PUT', 'PATCH']:
        data = request.get_json()
        if data and isinstance(data, dict) and 'token' in data:
            token = data.get('token')
    
    # 4. 备选方案：从Authorization头获取Bearer token
    if not token:
        auth_header = request.headers.get('Authorization')
        if auth_header and auth_header.startswith('Bearer '):
            token = auth_header[7:]  # 去掉'Bearer '前缀
    
    return token 